package cn.tedu._05mvcboot05.common.exception;

import cn.tedu._05mvcboot05.common.response.JsonResult;
import cn.tedu._05mvcboot05.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("MethodArgumentNotValidException=" + ex.getFieldError().getDefaultMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR, ex.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex) {
        String message=ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException=" + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }
}
